#!/bin/bash

# Replace with your container name
CONTAINER_NAME="zbp-env-server"
# 应用安装根目录
INSTALL_DIR="$ZBP_BASE_PATH/zbp/apps"
# 应用文件夹名称
PROJECT_INSTALL_DIR="env"
# 安装包下载地址
PACKAGE_URL="https://gitee.com/iamwx/deploy-files/raw/master/apps/target/common/env.tar.gz"

# 判断是否设置环境变量 $ZBP_BASE_PATH
if [ -z "$ZBP_BASE_PATH" ]; then
    echo "环境变量 ZBP_BASE_PATH 未设置，请先阅读文档 https://alidocs.dingtalk.com/i/nodes/dQPGYqjpJYgo29QesdPED3yLWakx1Z5N?doc_type=wiki_doc "
    exit 1
fi

# Function to check if a docker container is running
is_container_running() {
    container_name=$1
    if [ "$(docker ps -q -f name=^/${container_name}$)" ]; then
        return 0
    else
        return 1
    fi
}

# Check for Docker
if ! command -v docker &> /dev/null; then
    echo "Docker is not installed. Please install Docker and try again."
    exit 1
fi

# Check for Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo "Docker Compose is not installed. Please install Docker Compose and try again."
    exit 1
fi

# Check if specified Docker container is running
if is_container_running $CONTAINER_NAME; then
    echo "Docker container '$CONTAINER_NAME' is already running."
    exit 1
else
    echo "Docker container '$CONTAINER_NAME' is not running. Proceeding..."
fi

echo "初始化安装目录"
mkdir -p $INSTALL_DIR || { echo "无法创建安装目录: $INSTALL_DIR"; exit 1; }

echo "wget 校验"
if ! command -v wget &> /dev/null; then
    echo "wget 未安装，正在安装..."
    sudo yum install -y wget || { echo "wget 安装失败"; exit 1; }
fi

echo "判断文件夹是否存在"
if [ -d "$INSTALL_DIR/$PROJECT_INSTALL_DIR" ]; then
    echo "文件夹 $INSTALL_DIR/$PROJECT_INSTALL_DIR 已存在，结束安装"
    exit 1
else
    echo "4. 下载安装包到安装目录"
    cd $INSTALL_DIR || { echo "无法进入安装目录: $INSTALL_DIR"; exit 1; }
    wget $PACKAGE_URL -O $PROJECT_INSTALL_DIR.tar.gz || { echo "下载安装包失败: $PACKAGE_URL";exit 1; }
    if [ $? -eq 0 ]; then
        #
        echo "5. 解压安装包、删除安装包"
        tar -zxvf $PROJECT_INSTALL_DIR.tar.gz || { echo "解压安装包失败: $PROJECT_INSTALL_DIR.tar.gz"; exit 1; }
        rm -rf $PROJECT_INSTALL_DIR.tar.gz

    else
        echo "下载安装包失败: $PACKAGE_URL"
        exit 1
    fi
fi

echo "进入应用后端目录"
cd $INSTALL_DIR/$PROJECT_INSTALL_DIR/server || { echo "无法进入应用目录: $INSTALL_DIR/$PROJECT_INSTALL_DIR"; exit 1; }

echo "拉取最新镜像并 tag 为 docker-compose 文件里的名称"
docker pull registry.cn-hangzhou.aliyuncs.com/zyzbp-product/$CONTAINER_NAME:latest || { echo "拉取最新镜像失败"; exit 1; }
docker tag registry.cn-hangzhou.aliyuncs.com/zyzbp-product/$CONTAINER_NAME:latest $CONTAINER_NAME:latest || { echo "镜像打标签失败"; exit 1; }
docker rmi registry.cn-hangzhou.aliyuncs.com/zyzbp-product/$CONTAINER_NAME:latest || { echo "删除多余镜像失败"; exit 1; }

echo "启动应用"
docker-compose up -d || { echo "启动应用失败"; exit 1; }

echo "启动成功，过程中会重启一次，请稍后查看运行日志进行验证。"